package WebSocket;




import lombok.Data;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by tan on 2017/8/24.
 * 16:01
 */

@ServerEndpoint("/websocket/{roomid}")
public class WebsocketEndPoint {


    private  static int onlineCount=0;

    private static CopyOnWriteArraySet<WebsocketEndPoint> websocket = new CopyOnWriteArraySet<WebsocketEndPoint>();

    private Session session;

    private String roomid;

    @OnOpen
    public void onOpen(@PathParam("roomid") String roomid, Session session){
        this.session=session;
        this.roomid=roomid;
        System.out.println(roomid);
        System.out.println(session);
        websocket.add(this);
        addOnlineCount();
    }

    @OnClose
    public void onClose(){
        websocket.remove(this);
        subOnlineCounter();
        System.out.println("一个连接关闭");
    }

    @OnMessage
    public void onMessage(String message,Session session)
    {
        System.out.println("来自客户端的消息:"+session.getContainer()+" ");
        for(WebsocketEndPoint item:websocket){

            try{
                if (item!=this && this.roomid.equals(item.roomid)) item.sendMessage(message);
            }catch (IOException e)
            {
                e.printStackTrace();
                continue;
            }
        }

    }

    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }
    private void subOnlineCounter() {
        onlineCount--;
    }

    private void addOnlineCount() {
        onlineCount++;
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);

    }
    public Integer getAllCount(){
        return onlineCount;
    }

    public static String getRoomNumber(String roomid){
        int count = 0;
        for(WebsocketEndPoint item:websocket){

            try{
                if (item.roomid.equals(roomid)) count++;
            }catch (Exception e)
            {
                e.printStackTrace();
                continue;
            }
        }
        return new Integer(count).toString();
    }

}